<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="80px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="域名" prop="domain">
            <el-input v-model="queryParams.domain" placeholder="请输入域名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="版本类型" prop="versionType">
            <el-select v-model="queryParams.versionType" placeholder="请选择版本类型" clearable style="width: 240px">
              <el-option
                v-for="dict in logic_website_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="文字类型" prop="textType">
            <el-select v-model="queryParams.textType" placeholder="请选择文字类型" clearable style="width: 240px">
              <el-option
                v-for="dict in logic_language_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="空间大小" prop="spaceSize">
            <el-input v-model="queryParams.spaceSize" placeholder="请输入空间大小" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="已用空间大小" prop="usedSpaceSize">
            <el-input v-model="queryParams.usedSpaceSize" placeholder="请输入已用空间大小" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item> -->
          <el-form-item label="总流量" prop="totalTraffic">
            <el-input v-model="queryParams.totalTraffic" placeholder="请输入总流量" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="已用流量" prop="usedTraffic">
            <el-input v-model="queryParams.usedTraffic" placeholder="请输入已用流量" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="有效期始" prop="validFrom">
            <el-date-picker clearable
              v-model="queryParams.validFrom"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择有效期始"
               style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="有效期止" prop="validTo">
            <el-date-picker clearable
              v-model="queryParams.validTo"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择有效期止"
            />
          </el-form-item>
          <el-form-item label="创建人" prop="creator">
            <el-input v-model="queryParams.creator" placeholder="请输入创建人" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="更新人" prop="updater">
            <el-input v-model="queryParams.updater" placeholder="请输入更新人" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="是否生效" prop="isActive">
            <el-select v-model="queryParams.isActive" placeholder="请选择是否生效" clearable>
              <el-option
                v-for="dict in logic_isactive"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['logic:website:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['logic:website:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['logic:website:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['logic:website:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="websiteList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="网站ID" align="center" prop="websiteId" v-if="true" />
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="域名" align="center" prop="domain" />
        <el-table-column label="版本类型" align="center" prop="versionType">
          <template #default="scope">
            <dict-tag :options="logic_website_type" :value="scope.row.versionType"/>
          </template>
        </el-table-column>
        <el-table-column label="文字类型" align="center" prop="textType">
          <template #default="scope">
            <dict-tag :options="logic_language_type" :value="scope.row.textType"/>
          </template>
        </el-table-column>
        <el-table-column label="空间大小" align="center" prop="spaceSize" />
        <el-table-column label="已用空间大小" width="180" align="center" prop="usedSpaceSize" />
        <el-table-column label="总流量" align="center" prop="totalTraffic" />
        <el-table-column label="已用流量" align="center" prop="usedTraffic" />
        <el-table-column label="有效期始" align="center" prop="validFrom" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.validFrom, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="有效期止" align="center" prop="validTo" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.validTo, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="creator" />
        <el-table-column label="更新人" align="center" prop="updater" />
        <el-table-column label="是否生效" align="center" prop="isActive">
          <template #default="scope">
            <dict-tag :options="logic_isactive" :value="scope.row.isActive"/>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="270" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="生成静态文件" placement="top">
              <el-button link type="primary" icon="SetUp" @click="handleCreateStaticFile(scope.row)" v-hasPermi="['logic:website:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="发布" placement="top">
              <el-button link type="primary" icon="DocumentAdd" @click="handlePublish(scope.row)" v-hasPermi="['logic:website:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['logic:website:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['logic:website:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改站点管理对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="websiteFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="域名" prop="domain">
          <el-input v-model="form.domain" placeholder="请输入域名" />
        </el-form-item>
        <el-form-item label="版本类型" prop="versionType">
          <el-select v-model="form.versionType" placeholder="请选择版本类型">
            <el-option
                v-for="dict in logic_website_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文字类型" prop="textType">
          <el-select v-model="form.textType" placeholder="请选择文字类型">
            <el-option
                v-for="dict in logic_language_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="空间大小" prop="spaceSize">
          <el-input v-model="form.spaceSize" placeholder="请输入空间大小" />
        </el-form-item>
        <el-form-item label="已用空间大小" prop="usedSpaceSize">
          <el-input v-model="form.usedSpaceSize" placeholder="请输入已用空间大小" />
        </el-form-item>
        <el-form-item label="总流量" prop="totalTraffic">
          <el-input v-model="form.totalTraffic" placeholder="请输入总流量" />
        </el-form-item>
        <el-form-item label="已用流量" prop="usedTraffic">
          <el-input v-model="form.usedTraffic" placeholder="请输入已用流量" />
        </el-form-item>
        <el-form-item label="有效期始" prop="validFrom">
          <el-date-picker clearable
            v-model="form.validFrom"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择有效期始">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期止" prop="validTo">
          <el-date-picker clearable
            v-model="form.validTo"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择有效期止">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否生效" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择是否生效">
            <el-option
                v-for="dict in logic_isactive"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Website" lang="ts">
import { listWebsite, getWebsite, delWebsite, addWebsite, updateWebsite, publishWebsite } from '@/api/logic/website';
import { WebsiteVO, WebsiteQuery, WebsiteForm } from '@/api/logic/website/types';
import axios from 'axios';
import { saveEditorConfig } from '@/api/editor';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { logic_language_type, logic_website_type, logic_isactive } = toRefs<any>(proxy?.useDict('logic_language_type', 'logic_website_type', 'logic_isactive'));


const websiteList = ref<WebsiteVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const websiteFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: WebsiteForm = {
  websiteId: undefined,
  name: undefined,
  domain: undefined,
  versionType: undefined,
  textType: undefined,
  spaceSize: undefined,
  usedSpaceSize: undefined,
  totalTraffic: undefined,
  usedTraffic: undefined,
  validFrom: undefined,
  validTo: undefined,
  isActive: undefined
}
const data = reactive<PageData<WebsiteForm, WebsiteQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    domain: undefined,
    versionType: undefined,
    textType: undefined,
    spaceSize: undefined,
    usedSpaceSize: undefined,
    totalTraffic: undefined,
    usedTraffic: undefined,
    validFrom: undefined,
    validTo: undefined,
    creator: undefined,
    updater: undefined,
    isActive: undefined,
    params: {
    }
  },
  rules: {
    websiteId: [
      { required: true, message: "网站ID不能为空", trigger: "blur" }
    ],
    name: [
      { required: true, message: "名称不能为空", trigger: "blur" }
    ],
    domain: [
      { required: true, message: "域名不能为空", trigger: "blur" }
    ],
    versionType: [
      { required: true, message: "版本类型不能为空", trigger: "change" }
    ],
    textType: [
      { required: true, message: "文字类型不能为空", trigger: "change" }
    ],
    spaceSize: [
      { required: true, message: "空间大小不能为空", trigger: "blur" }
    ],
    usedSpaceSize: [
      { required: true, message: "已用空间大小不能为空", trigger: "blur" }
    ],
    totalTraffic: [
      { required: true, message: "总流量不能为空", trigger: "blur" }
    ],
    usedTraffic: [
      { required: true, message: "已用流量不能为空", trigger: "blur" }
    ],
    validFrom: [
      { required: true, message: "有效期始不能为空", trigger: "blur" }
    ],
    validTo: [
      { required: true, message: "有效期止不能为空", trigger: "blur" }
    ],
    isActive: [
      { required: true, message: "是否生效不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询站点管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listWebsite(queryParams.value);
  websiteList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  websiteFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: WebsiteVO[]) => {
  ids.value = selection.map(item => item.websiteId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加站点管理";
}

/**
 * 接受一个大驼峰格式字符串转换成短横线链接
 */
const toKebabCase = (str: string) => {
  const kebabCaseStr = str.replace(/([A-Z])/g, '-$1').toLowerCase();
  // 去掉开头的短横线
  return kebabCaseStr.replace(/^-/, '');
}

/**
 * 发布按钮操作
 */
const handlePublish = async (row?: WebsiteVO) => {
  const context = row?.context || '';
  if (!context) {
    proxy?.$modal.msgError("未获取到网站静态文件");
    return;
  }
  const _websiteId = row?.websiteId || ids.value[0]
  await publishWebsite(_websiteId);
  proxy?.$modal.msgSuccess("发布成功");
  // await getList();
}

const handleCreateStaticFile = async (row?: WebsiteVO) => {
  const _websiteId = row?.websiteId || ids.value[0]
  const res = await getWebsite(_websiteId);
  console.log(res);
  const data = res.data;
  if (data.websiteCompontRelations) {
    const websiteCompontRelations = data.websiteCompontRelations;
    console.log(websiteCompontRelations);
    if (websiteCompontRelations.length > 0) {
      const template = await axios.get('/template.html');
      // TODO 去掉换行符以及空格
      // let templateStr = template.data.replace(/\n/g, '').replace(/\s/g, '');
      let templateStr = template.data.replace(/\n/g, '');

      let str = 'const data = ref([';
      const componentRegist = [];
      const componentScript = [];
      for (const websiteCompontRelation of websiteCompontRelations) {
        const configJson = websiteCompontRelation.configJson == null ? '{}' : JSON.parse(websiteCompontRelation.configJson.replaceAll('\n', ''));
        const componentType = websiteCompontRelation.componentType == null ? '' : toKebabCase(websiteCompontRelation.componentType);
        str += `{name: '${componentType}', data: ${JSON.stringify(configJson)}},`;
        componentRegist.push(`app.component('${componentType}', ${websiteCompontRelation.componentType});`);

        const componentJson = websiteCompontRelation.componentJson == null ? [] : JSON.parse(websiteCompontRelation.componentJson);
        componentJson.forEach((e:any) => {
          componentScript.push(`<scripts src="${e.url}"></scripts>\n`.replaceAll('scripts', 'script'));
        });
      }
      str += ']);';
      templateStr = templateStr.replace('{{DATA_CONTENT}}', str);
      templateStr = templateStr.replace('{{COMPONENT_REGIST}}', componentRegist.join(''));
      templateStr = templateStr.replace('{{COMPONENT_SCRIPT}}', componentScript.join(''));
      templateStr += '\n';
      console.log(templateStr);

      const res = await updateWebsite({
        websiteId: data.websiteId,
        context: templateStr,
      });
      if (res.code == 200) {
        // proxy?.$modal.alertSuccess('网站配置保存成功');
        proxy?.$modal.msgSuccess('网站配置保存成功');
        getList();
      }
    }
  } else {
    proxy?.$modal.msgError("未获取到网站配置项");
  }
}

/** 修改按钮操作 */
const handleUpdate = async (row?: WebsiteVO) => {
  reset();
  const _websiteId = row?.websiteId || ids.value[0]
  const res = await getWebsite(_websiteId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改站点管理";
}

/** 提交按钮 */
const submitForm = () => {
  websiteFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.websiteId) {
        await updateWebsite(form.value).finally(() =>  buttonLoading.value = false);
      } else {
        await addWebsite(form.value).finally(() =>  buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: WebsiteVO) => {
  const _websiteIds = row?.websiteId || ids.value;
  await proxy?.$modal.confirm('是否确认删除站点管理编号为"' + _websiteIds + '"的数据项？').finally(() => loading.value = false);
  await delWebsite(_websiteIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('logic/website/export', {
    ...queryParams.value
  }, `website_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
});
</script>
